import React, { useEffect, useState } from 'react';
import GopherProps from '../objects/internal/GopherProps';
import BikeMap from '../components/BikeMap';
import OrderFilter from '../components/OrderFilter';
import './BikeMapFragment.css';
import { Order } from '../pouch/models/Order';
import { MapPoint } from '../pouch/models/City';
import { OrderFilterCondition } from '../objects/internal/OrderFilterCondition';
import { applyOrderFilter } from '../pouch/HyperFilter';
import { getCenter } from '../tooling/Map';

export default function BikeMapFragment(props: GopherProps) {
	const [polygons, setPolygons] = useState<MapPoint[][]>([]);
	const [dots, setDots] = useState<MapPoint[]>([]);
	const [loading, setLoading] = useState(false);
	const [center, setCenter] = useState<MapPoint>({ lng: 116.404269, lat: 39.910508 });

	const onFilterApplication = (filter: OrderFilterCondition) => {
		setLoading(true);
		applyOrderFilter(props.gopher, filter).then(result => {
			console.log(result.length);
			const points = result.map(it => it.currentPosition);
			setDots(result.map(it => it.currentPosition));
			if (points.length > 1) {
				setCenter(getCenter(points));
			}
			setLoading(false);
		});
	};

	useEffect(() => {
		props.gopher.listCities().then(result => {
			setPolygons(result.map(it => it.region));
			props.gopher.listOrders(0, 100).then(result => {
				setDots(result.data.map(it => (it as Order).currentPosition));
			})
		});
	}, [props.gopher]);

	return (
		<div className={'bike-map-wrapper'}>
			<div className={'bike-map-filter'}>
				<OrderFilter gopher={props.gopher} onSubmitButtonPressed={onFilterApplication} loading={loading} />
			</div>
			<div className={'bike-map-map'}>
				<BikeMap dots={dots} polygons={polygons} center={center} />
			</div>
		</div>
	);
}
